import React, { useState, useEffect, useCallback } from 'react'

import { message, Table, Image, Button, Space, Tag, Row, Col, Popconfirm, Drawer, Form, Input } from 'antd'
import { DeleteOutlined, FormOutlined, PlusOutlined, FileImageOutlined, ToTopOutlined } from '@ant-design/icons'
import { useNavigate, useSearchParams } from 'react-router-dom'
import axios from 'axios'
import request, { baseUrl } from '@/utils/request'
import { useStore, useSelector } from 'react-redux'

const List = () => {
    const [urlParams, setUrlParams] = useSearchParams()
    const [params, setParams] = useState({
        // 解决数据类型为string引起的bug
        page: Number(urlParams.get('page')) || 1,
        size: Number(urlParams.get('size')) || 10
    })
    const [total, setTotal] = useState(0)
    const navigate = useNavigate();

    // 创建表单实例
    const [myform] = Form.useForm()

    const [datalist, setDatalist] = useState([]);
    let controller
    const getData = async () => {
        controller = new AbortController()
        const { data } = await request.get('/category', {
            params,
            signal: controller.signal
        })

        setDatalist(data.data)
        setTotal(data.total)
    }

    const userInfo = useSelector((state) => state.userInfo)

    // 商品操作CRUD
    const removeItem = useCallback(async (id) => {
        console.log('id', id);
        const { data } = await request.post('/delCategory', { id })
        if (data.code === 200) {
            message.success('分类删除成功')
            // 刷新页面方案一：重新请求数据
            getData()

            // 刷新页面方案二：修改state达到刷新的效果
            // setDatalist(datalist.filter(item=>item._id != id))
        }
    }, [datalist])
    const [selectIds, setSelectIds] = useState([])
    const removeItems = useCallback(async () => {
        if (selectIds.length === 0) {
            return message.warning('请选择删除的分类');
        }
        const { data } = await request.post('/menu/delSome', {
            // headers: {
            //     Authorization: userInfo.authorization
            // },

            ids: selectIds

        })

        if (data.code === 200) {
            message.success('分类删除成功')
            getData()
        }
    }, [selectIds])
    //点击添加弹出抽屉
    const [open, setOpen] = useState(false);
    const addItem = useCallback(() => {
        setOpen(true);
    }, []);
    const onClose = () => {
        setOpen(false);
    };
    // 确定添加数据
    const onFinish = async (values) => {
        const { data } = await request.post('/addCategory', values)
        // console.log('addCategory', data);
        if (data.code === 200) {
            message.success('分类添加成功')
            getData();
            setOpen(false);
        }

    };

    //修改数据
    // console.log('datalist', datalist);
    // const [categorys, setCategorys] = useState([])
    const [editopen, seteditOpen] = useState(false);
    const [id, setId] = useState()
    const editItem = useCallback((id) => {
        seteditOpen(true);
        setId(id)
        console.log('editItem', id);
        // const newVal = { ...datalist, id: id }
        // console.log('categoryid', newVal);
        // const { data } = await request.post('/updateCategory', { ...datalist, id })
        // console.log('categoryid', data);
    }, [])
    const editonClose = () => {
        seteditOpen(false);
    };
    const editonFinish = async (values) => {
        console.log('values', values);
        const newVal = { ...values, id }
        console.log('newVal', newVal);
        const { data } = await request.post('/updateCategory', newVal)
        console.log('updateCategory', data);
        if (data.code === 200) {
            message.success('分类名称修改成功')
            getData();
            seteditOpen(false);
        }
    }
    // const [categoryname, setname] = useState('')
    // let categoryname = null
    const editvalue = async () => {
        const { data } = await request.get('/category/'+id ,{
            params:{
                id
            }
        })
        console.log('editvalue', data.data[0].category);
        if (data.code === 200) {
            // categoryname = data.data[0].category;
            // setname(data.data[0].category);
            myform.setFieldValue('category', data.data[0].category)
            // setname();
        }
    }
    // console.log(categoryname);
    useEffect(() => { editvalue() }, [id])

    // console.log('categoryname ' + categoryname);
    // editvalue()

    const columns = [
        {
            title: '#',
            key: '_id',
            width: 10,
            render(text, record, index) {
                return index + 1
            }
        },
        {
            title: '菜品分类',
            dataIndex: 'category',
            width: 180,
            //自定义单元格内容
            render: (text, record, index) => {
                // text: 当前列数据(dataIndex对应的数据，如无dataIndex,text与record一致)
                // record: 当前行数据
                // index: 当前索引值
                // console.log(text, record, index)
                return <h4>{text}</h4>
            }
        },
        {
            title: '添加时间',
            dataIndex: 'time',
            width: 120,
            render(time) {
                return <h4>{new Date().toLocaleDateString()}</h4>
            }
        },

        {
            title: '操作',
            dataIndex: 'id',
            width: 100,
            render(id) {
                return (
                    // <React.Fragment>
                    <Space>
                        <Button ghost type='primary' icon={<FormOutlined />} size="small" onClick={editItem.bind(null, id)}></Button>
                        <Popconfirm
                            title="确认删除"
                            onConfirm={removeItem.bind(null, id)}
                        >
                            <Button danger icon={<DeleteOutlined />} size="small"></Button>

                        </Popconfirm>
                    </Space>
                )
            }
        },
    ]
    const rowSelection = {
        onChange(selectedRowKeys) {
            console.log('selectedRowKeys=', selectedRowKeys)
            setSelectIds(selectedRowKeys)
        }
    }
    const pagination = {
        total,
        current: params.page,
        pageSize: params.size,
        size: 'small',
        onChange(page, size) {
            setParams({
                page,
                size
            })

            setUrlParams({
                page,
                size
            })
        }
    }


    useEffect(() => {
        getData();

        return function () {
            // 取消ajax
            controller.abort()
        }
    }, [params])



    return (
        <div>
            <Row gutter={20}>
                <Col span={8}>
                    <Button type='primary' icon={<PlusOutlined />} onClick={addItem}>添加</Button>
                </Col>
                <Col span={16} className='text-right'>
                    <Space>
                        <Button type='primary' ghost icon={<ToTopOutlined />}>上下架</Button>
                        <Popconfirm
                            title="确认删除"
                            onConfirm={removeItems}
                        >
                            <Button danger icon={<DeleteOutlined />}>批量删除</Button>

                        </Popconfirm>

                    </Space>
                </Col>
            </Row>
            <Table
                style={{ marginTop: 20 }}
                rowKey="id"
                rowSelection={rowSelection}
                columns={columns}
                dataSource={datalist}
                pagination={pagination}
            />
            <Drawer title="添加分类" placement="bottom" onClose={onClose} open={open} height='300px'>
                <Form
                    style={{ marginTop: '20px' }}
                    name="basic"
                    labelCol={{ span: 0 }}
                    wrapperCol={{ span: 24 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    // onFinishFailed={onFinishFailed}
                    autoComplete="off"
                    layout="vertical"
                >
                    <Form.Item
                        label={<div style={{ fontSize: 20 }} >分类名称</div>}
                        name="category"
                        rules={[{ required: true, message: '请输入分类名称!' }]}
                    >
                        <Input style={{ marginTop: 10, height: 40 }} />
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 0, span: 24 }}>
                        <Button type="primary" htmlType="submit" block style={{ height: 40, fontSize: 18 }} >
                            确认添加
                        </Button>
                    </Form.Item>
                </Form>
            </Drawer>
            <Drawer title="修改分类名称" placement="bottom" onClose={editonClose} open={editopen} height='300px'>
                <Form
                    style={{ marginTop: '20px' }}
                    name="basic"
                    labelCol={{ span: 0 }}
                    wrapperCol={{ span: 24 }}
                    // initialValues={{ categoryname }}
                    onFinish={editonFinish}
                    // onFinishFailed={onFinishFailed}
                    autoComplete="off"
                    layout="vertical"
                    form={myform}
                >
                    <Form.Item
                        label={<div style={{ fontSize: 20 }} >修改分类名称</div>}
                        name="category"
                        rules={[{ required: true, message: '请输入分类名称!' }]}
                    >
                        <Input style={{ marginTop: 10, height: 40 }} />
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 0, span: 24 }}>
                        <Button type="primary" htmlType="submit" block style={{ height: 40, fontSize: 18 }} >
                            确认修改
                        </Button>
                    </Form.Item>
                </Form>
            </Drawer>
        </div >

    )
}

export default List;